package com.edu.learning.concurrent.sample.mode1;

import java.util.concurrent.*;

/**
 * @author ll
 * @Date 2017/10/16 20:02
 */
public class ProducerConsumerDemo {

    private static final String FINISHED = "EOF";
    ExecutorService executorService = new ThreadPoolExecutor(
            8,
            8,
            0L,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(256),
            new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) {
        new ProducerConsumerDemo().testRun(new ConcurrentLinkedQueue());
    }

    private void testRun(ConcurrentLinkedQueue queue) {
        executorService.execute(new Producer(queue));
        executorService.execute(new Consumer(queue));
        executorService.shutdown();
    }

    static class Producer implements Runnable {
        private ConcurrentLinkedQueue<String> queue;

        public Producer(ConcurrentLinkedQueue<String> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            queue.offer("test");
            queue.offer(FINISHED);
        }
    }

    static class Consumer implements Runnable {
        private ConcurrentLinkedQueue<String> queue;

        public Consumer(ConcurrentLinkedQueue<String> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true) {
                String s = queue.poll();
                if (s != null) {
                    if (FINISHED.equalsIgnoreCase(s)) {
                        break;
                    }
                    System.out.println("Consumer输出 : Hello, " + s);
                }
            }
        }
    }
}
